package com.jming.yygh.msm.controller;

import com.jming.yygh.common.result.Result;
import com.jming.yygh.msm.service.MsmService;
import com.jming.yygh.msm.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author jming
 * @version 0.0.1
 * @date 2021/05/09
 */
@Api(value = "发送短信验证接口")
@RestController
@RequestMapping("/api/msm")
public class MsmApiController {

    @Resource
    private MsmService msmService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 根据手机号发送手机验证码
     * @param phone 手机号
     * @return Result 验证结果
     */
    @ApiOperation(value = "根据手机号发送手机验证码")
    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone) {

        // 从Redis中获取验证码，如果获取到，返回ok
        // key：手机号  valve：验证码
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return Result.ok();
        }

        // 如果获取不到，生成验证码
        // 生成验证码放入Redis里面，设置有效时间
        code = RandomUtil.getSixBitRandom();
        // 调用msmService方法，通过整短信服务进行发送
        boolean isSend = msmService.send(phone, code);

        // 判断验证码是否发送成功
        if (isSend) {
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return Result.ok();
        } else {
            return Result.fail().message("发送短信失败");
        }


    }

}
